import { createI18n } from 'vue-i18n'

import zh from './zh'

const messages = {
  zh,
}

const language = (navigator.language || 'en').toLocaleLowerCase(); 
const i18n = createI18n({
  locale: localStorage.getItem('lang') || language.split('-')[0] || 'zh',
  fallbackLocale: 'zh', // 设置备用语言
  messages,
})

export function t(key, locale) {
  if(!locale) {
    locale = localStorage.getItem('lang') || language.split('-')[0] || 'zh'
  }
  let k = key.split('.')
  if(k.length == 1) {
    return messages[locale][key]
  } else {
    return messages[locale][k[0]][k[1]]
  }
}

export function getLanguage() {
  return localStorage.getItem('lang') || language.split('-')[0] || 'zh'
}


export function setLanguage(item) {
  return localStorage.setItem('lang', item)
}

export default i18n